package com.ciccwm.dubbo.filter;

import com.ciccwm.log.context.TraceContext;
import com.ciccwm.log.util.TraceIdUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.common.constants.CommonConstants;
import org.apache.dubbo.common.extension.Activate;
import org.apache.dubbo.rpc.*;

/**
 * Dubbo链路追踪过滤器.
 */
@Slf4j
@Activate(group = CommonConstants.PROVIDER)
public class DubboTraceIdFilter implements Filter {

    @Override
    public Result invoke(Invoker<?> invoker, Invocation invocation) throws RpcException {
        try {
            String traceId = RpcContext.getServiceContext().getAttachment(TraceIdUtil.TRACE_ID_KEY);
            if (traceId == null) {
                traceId = TraceIdUtil.generateTraceId();
            }
            RpcContext.getServiceContext().setAttachment(TraceIdUtil.TRACE_ID_KEY, traceId);
            TraceContext.setTraceId(traceId);
            return invoker.invoke(invocation);
        } finally {
            TraceContext.removeTraceId();
        }
    }
} 
